package server.accessers.impl;

import org.omg.CORBA.Object;

import pds.uchiha.corba.manager.CorbaManager;
import server.accessers.DataReaderListenerOperations;
import server.accessers.DataReaderOperations;
import server.domaines.RemoteDomaineManager;
import server.domaines.RemoteDomaineManagerHelper;
import server.interfaces.Suscriber;
import server.operations.Operation;
import server.operations.OperationType;
import server.operations.Replicated;
import server.topic.impl.TopicImpl;

public class DataReaderImpl implements DataReaderOperations, DataReaderListenerOperations{
	
	private TopicImpl topic;
	
	public DataReaderImpl(TopicImpl topic) {
		this.topic = topic;
	}
	
	@Override
	public void signale() {
		Operation operation = topic.getSuscriber().read();
		executeOperation(operation);
		if(operation.replicated == Replicated.isReplicated){
			Object objRef = CorbaManager.getInstance().getReference("RemoteDomaine");
			RemoteDomaineManager domaine = RemoteDomaineManagerHelper.narrow(objRef);
			operation.replicated = Replicated.isNotReplicated;
			Suscriber[] suscribers = domaine.getTopicsSuscribers(topic.getFullName(), null);
			if(suscribers[0] == null)
				return;
			for(int i = 0;i<suscribers.length;i++){
				suscribers[i].publish(operation);
			}
		}
	}
	
	public void executeOperation(Operation operation){
		if(operation.target.equals("cache")){
			if(operation.type.value() == OperationType._create){
				topic.createCache();
			}
			if(operation.type.value() == OperationType._delete){
				topic.deleteCache();
			}
		}
		else if(operation.target.equals("topic")){
			if(operation.type.value() == OperationType._create){
				topic.createTopic(operation.data.data.extract_Value().toString());
			}
			else if(operation.type.value() == OperationType._delete){
				topic.deleteTopic(operation.data.data.extract_Value().toString());
			}
		}
	}
}
